package com.xxd.algo.myself.leetcode;


public class Problem_0092_ReverseBetween {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public static ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null) {
            return null;
        }
        ListNode result = head;
        int stepCn = right - left + 1;
        ListNode prefix = head;
        left--;
        while (left > 0) {
            prefix = head;
            head = head.next;
            left--;
        }

        ListNode last = head;
        ListNode cur = null;
        ListNode pre = head;
        while (last != null && stepCn > 0) {
            last = last.next;
            pre.next = cur;
            cur = pre;
            pre = last;
            stepCn--;
        }

        if (prefix != head) {
            prefix.next = cur;
            head.next = last;
            return result;
        } else {
            head.next = last;
            return cur;
        }
    }


    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode last = head;
        ListNode cur = null;
        ListNode pre = head;
        while (last != null) {
            last = last.next;
            pre.next = cur;
            cur = pre;
            pre = last;
        }

        return cur;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        head.next = new ListNode(5);

        reverseBetween(head, 1, 2);

    }
}
